package com.ghsc.yigou.live.ui.activity

import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.os.Bundle
import android.text.TextUtils
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alivc.auicommon.common.base.util.Utils
import com.alivc.auicommon.common.biz.exposable.enums.LiveStatus
import com.alivc.auicommon.common.roombase.Const
import com.alivc.auicommon.core.base.Actions
import com.alivc.auicommon.core.event.EventManager
import com.alivc.auimessage.MessageService
import com.alivc.auimessage.MessageServiceFactory
import com.alivc.auimessage.listener.InteractionCallback
import com.alivc.auimessage.model.base.InteractionError
import com.alivc.auimessage.model.lwp.GetGroupInfoRequest
import com.alivc.auimessage.model.lwp.GetGroupInfoResponse
import com.alivc.auimessage.model.lwp.JoinGroupRequest
import com.alivc.auimessage.model.lwp.JoinGroupResponse
import com.aliyun.aliinteraction.player.LivePlayerService
import com.aliyun.aliinteraction.player.LivePlayerServiceImpl
import com.aliyun.aliinteraction.roompaas.message.AUIMessageService
import com.aliyun.aliinteraction.roompaas.message.AUIMessageServiceFactory
import com.aliyun.aliinteraction.uikit.core.ComponentManager
import com.aliyun.aliinteraction.uikit.core.LiveConst
import com.aliyun.aliinteraction.uikit.uibase.util.DialogUtil
import com.aliyun.auiappserver.model.LiveModel
import com.aliyun.auipusher.AnchorPreviewHolder
import com.aliyun.auipusher.LiveContext
import com.aliyun.auipusher.LiveParam
import com.aliyun.auipusher.LiveRole
import com.aliyun.auipusher.LiveService
import com.aliyun.auipusher.LiveServiceImpl
import com.aliyun.auipusher.manager.LiveLinkMicPushManager
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.showToast
import com.ghsc.yigou.live.R

/**
 * 项目：YiGouLive
 * 包名：com.ghsc.yigou.live.ui.activity
 * 类名：LiveActivity
 * 创建时间：2024/8/5 16:30
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
class LiveActivity: AppCompatActivity() {



    var bundle : Bundle? =null
    var   pageParam: LiveParam? =null

    private var role: LiveRole? = null
    private var liveStatus: LiveStatus? = null
    private var liveId: String? = null
    private var liveModel: LiveModel? = null
    private var userNick: String? = null
    private var userExtension: String? = null
    private var groupId: String? = null
    private var tips: String? = null
    private var userAvatar: String? = null


    //消息服务  弹幕  开始直播 结束直播 更新 申请连麦 等
    private var auiMessageService: AUIMessageService? = null
    //交互
//    private var interactionService: InteractionService? = null

    //媒体推流服务
    private var pushManager: LiveLinkMicPushManager? = null
    //页面状态
    private var liveContext: LiveContext? = null


    //直播详情
    private var liveService: LiveService? = null
    //直播播放服务 播放 暂停 等
    private var livePlayerService: LivePlayerService? = null
    private val componentManager = ComponentManager()
    private val anchorPreviewHolder = AnchorPreviewHolder()

    private var messageService: MessageService? = null

    private var isPushing = false
    private var isFollow=false


    private val mHeadAdapter: LiveHeadListAdapter by lazy { LiveHeadListAdapter() }
    var mListHead = arrayListOf<String>()


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_live2)
        initView()
    }

    fun initView(){
        bundle = intent.extras
        pageParam = intent.getSerializableExtra(LiveConst.PARAM_KEY_LIVE_PARAM) as LiveParam?
        pageParam?.let {
            liveId = it.liveId
            liveModel = it.liveModel
            role = it.role
            liveStatus = LiveStatus.of(liveModel!!.status)
            userNick = it.userNick
            userAvatar = it.userAvatar
            userExtension = it.userExtension
            tips = pageParam!!.notice
            groupId = liveModel!!.chatId
            loge("liveModel=" + liveModel)
        }
        // 获取RoomChannel
        messageService = MessageServiceFactory.getMessageService()
        if (!messageService!!.isLogin) {
            showToast("未登录")
            finish()
            return
        }

        pushManager = LiveLinkMicPushManager(this, null)

        liveContext = LiveContextImpl()
        val decorView = window.decorView
        componentManager.scanComponent(decorView)
        componentManager.dispatchInit(liveContext!!)
        joinGroup()


    }

    private fun isActivityValid(): Boolean {
        return !isFinishing && !isDestroyed
    }
    private fun onEnterRoomError(errorMsg: String) {
        componentManager.dispatchEnterRoomError(errorMsg)
    }
    private fun onEnterRoomSuccess(liveModel: LiveModel) {
        this.liveModel = liveModel
        componentManager.dispatchEnterRoomSuccess(liveModel)
        val request = GetGroupInfoRequest()
        request.groupId = groupId
        auiMessageService!!.messageService.getGroupInfo(
            request,
            object : InteractionCallback<GetGroupInfoResponse?> {
                override fun onSuccess(response: GetGroupInfoResponse?) {
                    if (Utils.isActivityValid(this@LiveActivity)) {
                        componentManager.post(Actions.GET_GROUP_STATISTICS_SUCCESS, response)
                    }
                }

                override fun onError(error: InteractionError) {}
            })
    }
    private fun joinGroup() {
        val request = JoinGroupRequest()
        request.groupId = groupId
        messageService!!.joinGroup(request, object : InteractionCallback<JoinGroupResponse?> {
            override fun onSuccess(data: JoinGroupResponse?) {
                if (isActivityValid()) {
                    onEnterRoomSuccess(liveModel!!)
                }
            }

            override fun onError(error: InteractionError) {
                if (isActivityValid()) {
                    onEnterRoomError(error.msg)
                    // 进入失败时, 退出房间
                    val message = String.format("进入房间失败：\n%s", error.msg)
                    DialogUtil.confirm(this@LiveActivity, message,
                        { finish() }
                    ) { finish() }
                }
            }
        })
    }

    /**
     * 当系统的配置信息发生改变时，系统会调用此方法。注意，只有在配置文件AndroidManifest中处理了configChanges属性对应的设备配置，该方法才会被调用。
     * 如果发生设备配置与在配置文件中设置的不一致，则Activity会被销毁并使用新的配置重建。
     * 例如：当屏幕方向发生改变时，Activity会被销毁重建，如果在AndroidManifest文件中处理屏幕方向配置信息如下
     */
    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        componentManager.dispatchActivityConfigurationChanged(newConfig)
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        componentManager.dispatchActivityResult(requestCode, resultCode, data)
    }
    override fun onPause() {
        super.onPause()
        componentManager.dispatchActivityPause()
    }

    override fun onResume() {
        super.onResume()
        componentManager.dispatchActivityResume()
    }

    override fun onBackPressed() {
        if (!componentManager.interceptBackKey()) {
            super.onBackPressed()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        componentManager.dispatchActivityDestroy()
        liveContext!!.messageService.removeAllMessageListeners()
    }

    override fun finish() {
        super.finish()
        componentManager.dispatchActivityFinish()
    }
    inner class LiveContextImpl : LiveContext {
        override fun getActivity(): Activity {
            return this@LiveActivity
        }

        override fun getRole(): LiveRole {
            return this@LiveActivity.role!!
        }

        override fun getNick(): String {
            return this@LiveActivity.userNick!!
        }
        override fun getAvatar(): String {
            return this@LiveActivity.userAvatar!!
        }
        override fun getTips(): String {
            return this@LiveActivity.tips!!
        }

        override fun getLiveStatus(): LiveStatus {
            return this@LiveActivity.liveStatus!!
        }

        override fun getEventManager(): EventManager {
            return this@LiveActivity.componentManager
        }

        override fun isPushing(): Boolean {
            return this@LiveActivity.isPushing
        }

        override fun setPushing(isPushing: Boolean) {
            this@LiveActivity.isPushing = isPushing
        }
        override fun isFollow(): Boolean {
            return this@LiveActivity.isFollow
        }
        override fun isLandscape(): Boolean {
            return this@LiveActivity.resources
                .configuration.orientation == Configuration.ORIENTATION_LANDSCAPE
        }

        override fun setLandscape(landscape: Boolean) {
            if (landscape) {
                // 竖屏 => 横屏
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
            } else {
                // 横屏 => 竖屏
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
            }
        }

        override fun getLiveId(): String {
            return this@LiveActivity.liveId!!
        }

        override fun getGroupId(): String {
            return this@LiveActivity.groupId!!
        }

        override fun getUserId(): String {
            return Const.getUserId()
        }

        override fun getLiveService(): LiveService {
            if (this@LiveActivity.liveService == null) {
                this@LiveActivity.liveService = LiveServiceImpl(this@LiveActivity, liveContext)
            }
            return this@LiveActivity.liveService!!
        }

        override fun getLivePlayerService(): LivePlayerService {
            if (this@LiveActivity.livePlayerService == null) {
                this@LiveActivity.livePlayerService = LivePlayerServiceImpl(this@LiveActivity)
            }
            return this@LiveActivity.livePlayerService!!
        }

        override fun getMessageService(): AUIMessageService {
            if (this@LiveActivity.auiMessageService == null) {
                this@LiveActivity.auiMessageService = AUIMessageServiceFactory.getMessageService(groupId)
            }
            return this@LiveActivity.auiMessageService!!
        }

        override fun getLiveLinkMicPushManager(): LiveLinkMicPushManager {
            return this@LiveActivity.pushManager!!
        }

        override fun getLiveModel(): LiveModel {
            return this@LiveActivity.liveModel!!
        }

        override fun getAnchorPreviewHolder(): AnchorPreviewHolder {
            return this@LiveActivity.anchorPreviewHolder
        }

        override fun isOwner(userId: String): Boolean {
            if (liveModel != null) {
                val anchorId = liveModel.anchorId
                if (!TextUtils.isEmpty(anchorId)) {
                    return TextUtils.equals(anchorId, userId)
                }
            }
            return false
        }
    }


}